package com.gzc.just.play.last.war.centralserver;

import com.gzc.just.play.last.war.common.handler.VirtualThreadNettyServer;
import com.gzc.just.play.last.war.common.handler.VirtualThreadServerFramework;
import com.gzc.just.play.last.war.centralserver.handler.*;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Central Server的Netty服务器实现
 * 使用虚拟线程处理中心服务器请求
 */
@Component("central-centralNettyServer")
public class CentralNettyServer extends VirtualThreadNettyServer {

    private static final Logger logger = LoggerFactory.getLogger(CentralNettyServer.class);

    @Value("${central.server.port:6001}")
    private int centralServerPort;
    
    @Value("${central.server.host:127.0.0.1}")
    private String centralServerHost;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    protected int getNettyPort() {
        return centralServerPort;
    }
    
    @Override
    protected String getNettyHost() {
        return centralServerHost;
    }

    @Override
    protected VirtualThreadServerFramework.ServerType getServerType() {
        return VirtualThreadServerFramework.ServerType.CENTRAL_SERVER;
    }
    
    @Override
    protected void initializeHandlers() {
        // 从Spring容器获取Handler以确保依赖注入生效
        try {
            if (applicationContext != null) {
                framework.registerHandler(applicationContext.getBean(ServerStatusHandler.class));
                framework.registerHandler(applicationContext.getBean(UserMessageHandler.class));
                framework.registerHandler(applicationContext.getBean(MatchmakingHandler.class));
                framework.registerHandler(applicationContext.getBean(RankingHandler.class));
                framework.registerHandler(applicationContext.getBean(ReportGCMsgHandler.class)); // 新增的Handler
                
                logger.info("Initialized {} handlers for Central Server from Spring context", framework.getHandlerManager().getHandlerCount());
            } else {
                logger.error("ApplicationContext is null, cannot register handlers correctly!");
            }
        } catch (Exception e) {
            logger.error("Error initializing Central Server handlers", e);
        }
    }
    
    @Override
    protected void onConnectionActive(ChannelHandlerContext ctx) {
        super.onConnectionActive(ctx);
        logger.debug("New central connection from: {}", ctx.channel().remoteAddress());
    }
    
    @Override
    protected void onConnectionInactive(ChannelHandlerContext ctx) {
        super.onConnectionInactive(ctx);
        logger.debug("Central connection closed from: {}", ctx.channel().remoteAddress());
    }
}